<template>
    <div class="addGoods">
      <el-card class="box-card">
        <!--    面包屑导航-->
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
          </el-breadcrumb>
      </el-card>
      <el-card class="box-card">
        <el-steps :space="200" :active="step.active" finish-status="success" align-center>
          <el-step :title="step.active > 1 ? '已完成' : '进行中'" description="给您的商品定个位吧~"></el-step>
          <el-step :title="step.active > 2 ? '已完成' : '进行中'" description="这些信息会展示在商品详情的哦~"></el-step>
          <el-step :title="step.active > 3 ? '已完成' : '进行中'" description="多种多样的商品能更吸引顾客哦~"></el-step>
          <el-step :title="step.active > 4 ? '已完成' : '进行中'" description="快完成啦~"></el-step>
          <el-step :title="step.active > 5 ? '已完成' : '进行中'" description="这是最后最重要的一步了~"></el-step>
        </el-steps>

        <el-form :model="spu" :rules="rules" ref="Form1" label-width="100px" class="demo-ruleForm" v-show="step.active == 1">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="spu.name"></el-input>
          </el-form-item>
          <el-form-item label="副标题" prop="caption">
            <el-input v-model="spu.caption"></el-input>
          </el-form-item>
          <el-form-item label="商品品牌" prop="brandId" >
            <template>
              <el-select v-model="spu.brandId" placeholder="请选择">
                <el-option
                  v-for="item in brandList"
                  :key="item.id"
                  :label="item.chineseName"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-cascader
              v-model="category"
              :options="options"
              placeholder="下拉选择商品分类"
              @change="handleChange">
            </el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button @click="toForm2()" type="primary" :disabled="isSearch">下一步</el-button>
          </el-form-item>
        </el-form>

        <el-form label-width="160px" v-show="step.active == 2">
          <div  v-for="(specGroup,index) in generalSpecGroupList" :key="index">
            <h3 v-text="specGroup.name" v-show="specGroup.groupParam.length !== 0"></h3>
            <div v-for="specParam in specGroup.groupParam" :key="specParam.id">

              <el-form-item :label="specParam.name" v-if="specParam.size !== 0  && specParam.type === 0">
                <!--            自定义字符串类型-->
                <el-input
                  type="text"
                  v-model="spu.specList[specParam.id]"
                  v-show="specParam.options.length === 0"
                  maxlength="100"
                  show-word-limit
                ></el-input>
                <!--            选填字符串类型-->
                <el-select
                  v-model="spu.specList[specParam.id]"
                  placeholder="请选择"
                  v-show="specParam.options.length !== 0"
                >
                  <el-option
                    v-for="option in specParam.options.split(',')"
                    :key="option"
                    :label="option"
                    :value="option">
                  </el-option>
                </el-select>
              </el-form-item>


              <el-form-item :label="specParam.name" v-else-if="specParam.size !== 0 && specParam.type === 1">
                <!--            自定义数值类型-->
                <el-input
                  type="number"
                  v-model.number="spu.specList[specParam.id]"
                  v-show="specParam.options.length === 0"
                ></el-input>
                <!--            选添数值类型-->
                <el-select
                  v-model.number="spu.specList[specParam.id]"
                  placeholder="请选择"
                  v-show="specParam.options.length !== 0"
                >
                  <el-option
                    v-for="option in specParam.options.split(',')"
                    :key="option"
                    :label="option"
                    :value="option">
                  </el-option>
                </el-select>
              </el-form-item>


              <el-form-item :label="specParam.name"
                            v-else-if="specParam.size !== 0 && specParam.options.length === 0 || specParam.type === 2 || specParam.type === 3 || specParam.type === 4 || specParam.type === 5">
                <!--            日期(年)类型-->
                <el-date-picker
                  v-model.number="spu.specList[specParam.id]"
                  v-show="specParam.type === 2"
                  type="year"
                  placeholder="选择年">
                </el-date-picker>
                <!--            日期(年月)类型-->
                <el-date-picker
                  v-model="spu.specList[specParam.id]"
                  v-show="specParam.type === 3"
                  type="month"
                  placeholder="选择月">
                </el-date-picker>
                <!--            日期(年月日)类型-->
                <el-date-picker
                  v-model="spu.specList[specParam.id]"
                  v-show="specParam.type === 4"
                  type="date"
                  placeholder="选择日期">
                </el-date-picker>
                <!--            日期(年月日时分秒)类型-->
                <el-date-picker
                  v-model="spu.specList[specParam.id]"
                  v-show="specParam.type === 5"
                  type="datetime"
                  placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>


              <el-form-item :label="specParam.name" v-else>
                <!--            集合类型-->
                <el-select
                  v-model="spu.specList[specParam.id]"
                  multiple placeholder="请选择"
                >
                  <el-option
                    v-for="option in specParam.options.split(',')"
                    :key="option"
                    :label="option"
                    :value="option">
                  </el-option>
                </el-select>
              </el-form-item>

            </div>
          </div>
          <el-form-item>
            <el-button @click="beforeStep" type="info">上一步</el-button>
            <el-button @click="toForm3()" type="primary">下一步</el-button>
          </el-form-item>
        </el-form>


        <el-form v-show="step.active == 3" label-width="160px">
<!--          <el-form-item label="请选择子商品个数">-->
<!--            <el-select v-model="skuNum" placeholder="请选择">-->
<!--              <el-option-->
<!--                v-for="i in 10"-->
<!--                :key="i"-->
<!--                :label="i"-->
<!--                :value="i">-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->

          <div  v-for="(specGroup,i) in unGeneralSpecGroupList" :key="i">
            <h3 v-text="specGroup.name" v-show="specGroup.groupParam.length !== 0"></h3>
            <div v-for="(specParam, specInde) in specGroup.groupParam" :key="specInde">

              <el-form-item :label="specParam.name" v-if="specParam.size !== 0  && specParam.type === 0">
                <!--            自定义字符串类型-->
                <el-input
                  type="text"
                  v-model="skuSpecList[specParam.id]"
                  v-show="specParam.options.length === 0"
                  maxlength="100"
                  show-word-limit
                ></el-input>
                <!--            选填字符串类型-->
                <el-select
                  v-model="skuSpecList[specParam.id]"
                  placeholder="请选择"
                  v-show="specParam.options.length !== 0"
                >
                  <el-option
                    v-for="option in specParam.optionsAndUnit.split(',')"
                    :key="option"
                    :label="option"
                    :value="option">
                  </el-option>
                </el-select>
              </el-form-item>


              <el-form-item :label="specParam.name" v-else-if="specParam.size !== 0 && specParam.type === 1">
                <!--            自定义数值类型-->
                <el-input
                  type="number"
                  v-model.number="skuSpecList[specParam.id]"
                  v-show="specParam.options.length === 0"
                ></el-input>
                <!--            选添数值类型-->
                <el-select
                  v-model.number="skuSpecList[specParam.id]"
                  placeholder="请选择"
                  v-show="specParam.options.length !== 0"
                >
                  <el-option
                    v-for="option in specParam.optionsAndUnit.split(',')"
                    :key="option"
                    :label="option"
                    :value="option">
                  </el-option>
                </el-select>
              </el-form-item>


              <el-form-item :label="specParam.name"
                            v-else-if="specParam.size !== 0 && specParam.options.length === 0 || specParam.type === 2 || specParam.type === 3 || specParam.type === 4 || specParam.type === 5">
                <!--            日期(年)类型-->
                <el-date-picker
                  v-model.number="skuSpecList[specParam.id]"
                  v-show="specParam.type === 2"
                  type="year"
                  placeholder="选择年">
                </el-date-picker>
                <!--            日期(年月)类型-->
                <el-date-picker
                  v-model="skuSpecList[specParam.id]"
                  v-show="specParam.type === 3"
                  type="month"
                  placeholder="选择月">
                </el-date-picker>
                <!--            日期(年月日)类型-->
                <el-date-picker
                  v-model="skuSpecList[specParam.id]"
                  v-show="specParam.type === 4"
                  type="date"
                  placeholder="选择日期">
                </el-date-picker>
                <!--            日期(年月日时分秒)类型-->
                <el-date-picker
                  v-model="skuSpecList[specParam.id]"
                  v-show="specParam.type === 5"
                  type="datetime"
                  placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>


              <el-form-item :label="specParam.name" v-else>
                <!--            集合类型-->
                <el-select
                  v-model="skuSpecList[specParam.id]"
                  multiple placeholder="请选择"
                >
                  <el-option
                    v-for="option in specParam.optionsAndUnit.split(',')"
                    :key="option"
                    :label="option"
                    :value="option">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>


          <el-table
            :data="skuList"
            style="width: 100%">
            <el-table-column
              prop="name"
              label="商品名称"
              width="250">
            </el-table-column>
            <el-table-column
              label="价格"
              width="250">
              <template slot-scope="scope">
                <input type="number" style="" v-model="scope.row.price">
              </template>
            </el-table-column>
            <el-table-column
              label="库存"
              width="250"
            >
              <template slot-scope="scope">
                <input type="number" style="" v-model="scope.row.num">
              </template>
            </el-table-column>
            <el-table-column
              label="图片"
              width="450"
            >
              <template slot-scope="scope">
                <el-upload
                  action="http://localhost:8001/api/file/index/upload"
                  class="upload-demo"
                  name="file"
                  :data="{'index': scope.$index}"
                  :headers=headers
                  :file-list="scope.row.imageList"
                  :on-success="handleSuccess"
                  :on-remove="handleRemove"
                  list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过20M</div>
                </el-upload>
              </template>
            </el-table-column>
          </el-table>

          <!--<div v-for="index in skuNum" :key="index">
            <h2 v-text="'sku商品'+index" style="color: #409eff"></h2>
            <el-form-item label="sku名称">
              <el-input v-model="skuList[index-1].name"></el-input>
            </el-form-item>
            <el-form-item label="价格">
              <el-input type="number" v-model="skuList[index-1].price"></el-input>
            </el-form-item>
            <el-form-item label="库存">
              <el-input type="number" v-model="skuList[index-1].num"></el-input>
            </el-form-item>
            <el-form-item label="图片列表">
&lt;!&ndash;              :file-list="skuList[index-1].imageList"&ndash;&gt;
              <el-upload
                action="http://localhost:8001/api/file/index/upload"
                class="upload-demo"
                name="file"
                :data="{'index': index-1}"
                :headers=headers
                :file-list="skuList[index -1].imageList"
                :on-success="handleSuccess"
                :on-remove="handleRemove"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过20M</div>
              </el-upload>
            </el-form-item>
            <div  v-for="(specGroup,i) in unGeneralSpecGroupList" :key="i">
              <h3 v-text="specGroup.name" v-show="specGroup.groupParam.length !== 0"></h3>
              <div v-for="specParam in specGroup.groupParam" :key="specParam.id">

                <el-form-item :label="specParam.name" v-if="specParam.size !== 0  && specParam.type === 0">
                  &lt;!&ndash;            自定义字符串类型&ndash;&gt;
                  <el-input
                    type="text"
                    v-model="skuList[index-1].specList[specParam.id]"
                    v-show="specParam.options.length === 0"
                    maxlength="100"
                    show-word-limit
                  ></el-input>
                  &lt;!&ndash;            选填字符串类型&ndash;&gt;
                  <el-select
                    v-model="skuList[index-1].specList[specParam.id]"
                    placeholder="请选择"
                    v-show="specParam.options.length !== 0"
                  >
                    <el-option
                      v-for="option in specParam.options.split(',')"
                      :key="option"
                      :label="option"
                      :value="option">
                    </el-option>
                  </el-select>
                </el-form-item>


                <el-form-item :label="specParam.name" v-else-if="specParam.size !== 0 && specParam.type === 1">
                  &lt;!&ndash;            自定义数值类型&ndash;&gt;
                  <el-input
                    type="number"
                    v-model.number="skuList[index-1].specList[specParam.id]"
                    v-show="specParam.options.length === 0"
                  ></el-input>
                  &lt;!&ndash;            选添数值类型&ndash;&gt;
                  <el-select
                    v-model.number="skuList[index-1].specList[specParam.id]"
                    placeholder="请选择"
                    v-show="specParam.options.length !== 0"
                  >
                    <el-option
                      v-for="option in specParam.options.split(',')"
                      :key="option"
                      :label="option"
                      :value="option">
                    </el-option>
                  </el-select>
                </el-form-item>


                <el-form-item :label="specParam.name"
                              v-else-if="specParam.size !== 0 && specParam.options.length === 0 || specParam.type === 2 || specParam.type === 3 || specParam.type === 4 || specParam.type === 5">
                  &lt;!&ndash;            日期(年)类型&ndash;&gt;
                  <el-date-picker
                    v-model.number="skuList[index-1].specList[specParam.id]"
                    v-show="specParam.type === 2"
                    type="year"
                    placeholder="选择年">
                  </el-date-picker>
                  &lt;!&ndash;            日期(年月)类型&ndash;&gt;
                  <el-date-picker
                    v-model="skuList[index-1].specList[specParam.id]"
                    v-show="specParam.type === 3"
                    type="month"
                    placeholder="选择月">
                  </el-date-picker>
                  &lt;!&ndash;            日期(年月日)类型&ndash;&gt;
                  <el-date-picker
                    v-model="skuList[index-1].specList[specParam.id]"
                    v-show="specParam.type === 4"
                    type="date"
                    placeholder="选择日期">
                  </el-date-picker>
                  &lt;!&ndash;            日期(年月日时分秒)类型&ndash;&gt;
                  <el-date-picker
                    v-model="skuList[index-1].specList[specParam.id]"
                    v-show="specParam.type === 5"
                    type="datetime"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </el-form-item>


                <el-form-item :label="specParam.name" v-else>
                  &lt;!&ndash;            集合类型&ndash;&gt;
                  <el-select
                    v-model="skuList[index-1].specList[specParam.id]"
                    multiple placeholder="请选择"
                  >
                    <el-option
                      v-for="option in specParam.options.split(',')"
                      :key="option"
                      :label="option"
                      :value="option">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>
          </div>-->
          <el-form-item style="margin-top: 10px">
            <el-button @click="beforeStep" type="info">上一步</el-button>
            <el-button @click="toForm4()" type="primary">下一步</el-button>
          </el-form-item>
        </el-form>


        <el-form v-show="step.active == 4">
          <el-form-item  prop="content">
            <el-tiptap
              v-model="spu.introduction"
              :extensions="extensions"
              height="350"
              placeholder="请输入商品描述"
            ></el-tiptap>
          </el-form-item>
          <el-form-item>
            <el-button @click="beforeStep" type="info">上一步</el-button>
            <el-button @click="toForm5()" type="primary">下一步</el-button>
          </el-form-item>
        </el-form>

        <el-form v-show="step.active == 5">
          <el-form-item  prop="content">
            <el-tiptap
              v-model="spu.afterService"
              :extensions="extensions"
              height="350"
              placeholder="请输入商品售后"
            ></el-tiptap>
          </el-form-item>
          <el-form-item>
            <el-button @click="beforeStep" type="info">上一步</el-button>
            <el-button @click="addGoods" :loading="isAdding" type="primary">提交</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
</template>

<script>
import { getBrandTree } from '@/api/category'
import { getAllBrand } from '@/api/brand'
import { findGeneralSpecGroupByCategoryId, findUnGeneralSpecGroupByCategoryId } from '@/api/spec'
import { Message } from 'element-ui'
import { uploadImage, deleteImage } from '@/api/image'
import { addSpu } from '@/api/goods'
import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Image,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  TodoItem,
  TodoList,
  HorizontalRule,
  Fullscreen,
  Preview,
  CodeBlock,
  TextColor
} from 'element-tiptap'
export default {
  name: 'AddGoods',
  components: {
    'el-tiptap': ElementTiptap
  },
  props: {},
  data () {
    return {
      step: {
        active: 1 // 步骤条激活状态初始化
      },
      spu: {
        name: '', // spu名称
        caption: '', // 副标题
        brandId: '', // 品牌ID
        category1Id: 0, // 一级分类
        category2Id: 0, // 二级分类
        category3Id: 0, // 三级分类
        afterService: '', // 售后服务
        specList: [], // 规格列表
        introduction: '' // 商品介绍
      },
      skuList: [], // sku集合
      category: [], // 类目选框绑定集合
      skuSpecList: [], // sku的spc集合
      brandList: [], // 品牌集合
      options: [], // 树形类目列表数组
      generalSpecGroupList: [], // 根据三级目录获取到的通用规格列表
      unGeneralSpecGroupList: [], // 根据三级目录获取到的非通用规格列表
      skuNum: 0, // 商品sku数量
      currentSkuIndex: 1, // 当前编辑sku下标
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      isAdding: false, // 添加loading开关
      isSearch: false, // 搜索按钮开关
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { max: 100, message: '长度在100个字符以内', trigger: 'blur' }
        ],
        caption: [
          { required: true, message: '请填写副标题', trigger: 'blur' },
          { max: 100, message: '长度在100个字符以内', trigger: 'blur' }
        ],
        brandId: [
          { required: true, message: '请选择商品品牌', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ]
      },
      // 编辑器的 extensions
      // 它们将会按照你声明的顺序被添加到菜单栏和气泡菜单中
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 3 }),
        new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
        new Image({
          // 默认会把图片生成 base64 字符串和内容存储在一起，如果需要自定义图片上传
          uploadRequest (file) {
            // 如果接口要求 Content-Type 是 multipart/form-data，则请求体必须使用 FormData
            const fd = new FormData()
            fd.append('file', file)
            // 第1个 return 是返回 Promise 对象
            // 为什么？因为 axios 本身就是返回 Promise 对象
            return uploadImage(fd).then(res => {
              // 这个 return 是返回最后的结果
              return res.data.data
            })
          } // 图片的上传方法，返回一个 Promise<url>
        }),
        new Underline(), // 下划线
        new Italic(), // 斜体
        new Strike(), // 删除线
        new HorizontalRule(), // 华丽的分割线
        new ListItem(),
        new BulletList(), // 无序列表
        new OrderedList(), // 有序列表
        new TodoItem(),
        new TodoList(),
        new Fullscreen(),
        new Preview(),
        new CodeBlock(),
        new TextColor()
      ]
    }
  },
  computed: {
    headers () {
      return {
        Authorization: window.sessionStorage.getItem('accessToken').toString() // 直接从本地获取token就行
      }
    }
  },
  watch: {
    // 监听sku的spec集合的变化
    skuSpecList: {
      deep: true, // 深度监听设置为 true
      handler: function (newValue, oldValue) {
        // 监听似乎监听不到旧数据。。。。
        // console.log('newValue', newValue)
        // console.log('oldValue', oldValue)
        var oldSkuNum = this.skuNum
        this.skuNum = 0
        var list = []
        var indexList = []
        var j = 0
        for (let i = 0; i < newValue.length; i++) {
          if (newValue[i] !== undefined) {
            if (newValue[i].length !== 0) {
              this.skuNum = this.skuNum === 0 ? newValue[i].length : this.skuNum * newValue[i].length
              // 添加一份到spu里
              this.spu.specList[i] = newValue[i]
              list[j] = newValue[i]
              indexList[j] = i
              j++
            }
          }
        }

        // 先清理skuList
        this.skuList.forEach(sku => {
          sku.name = ''
          sku.specList = []
          if (sku.imageList.length !== 0) {
            // 还有图片
            sku.imageList.forEach(image => {
              deleteImage(image).then(resp => {
                // 删除成功
                if (resp.data.code === 20000) {
                  sku.imageList = []
                  Message({
                    type: 'success',
                    message: resp.data.message
                  })
                } else {
                  Message({
                    type: 'warning',
                    message: resp.data.message
                  })
                }
              }).catch(() => {})
            })
          }
        })

        // 增加sku
        if (this.skuNum >= oldSkuNum) {
          // 增加
          // console.log('增加sku')
          for (let i = 0; i < this.skuNum - oldSkuNum; i++) {
            this.skuList.push({
              name: '', // sku名称
              price: 0, // 价格
              num: 0, // 库存
              imageList: [], // 图片列表
              specList: [] // 规格列表
            })
          }
        } else {
          // 减少
          // console.log('减少' + (oldSkuNum - this.skuNum) + 'sku')
          for (let i = 0; i < oldSkuNum - this.skuNum; i++) {
            this.skuList.pop(1)
          }
        }

        var duan = this.skuNum
        for (let i = 0; i < list.length; i++) {
          var lh = list[i].length
          duan = duan / lh
          for (let k = 0; k < lh; k++) {
            for (let l = 0; ; l++) {
              if (lh * duan * l === this.skuNum) {
                break
              }
              for (let m = lh * duan * l + duan * k; m < lh * duan * l + duan * k + duan; m++) {
                // console.log(i + '' + lh + '' + duan + '' + k + '' + l + '' + m + '')
                // this.skuList[m].name += ' ' + (this.list[i])[k + m - duan * l - k * (duan / lh)]
                this.skuList[m].name += ' ' + (list[i])[k]
                this.skuList[m].specList[indexList[i]] = (list[i])[k]
              }
            }
          }
        }
      }
    },
    // 监听sku数量变化
    /* skuNum: {
      handler: function (newValue, oldValue) {
        if (newValue > oldValue) {
          // 增加
          for (let i = 0; i < newValue - oldValue; i++) {
            this.skuList.push({
              name: '', // sku名称
              price: 0, // 价格
              num: 0, // 库存
              imageList: [], // 图片列表
              specList: [] // 规格列表
            })
          }
        } else {
          // 减少
          for (let i = 0; i < oldValue - newValue; i++) {
            var p = this.skuList.pop(1)
            if (p.imageList.length !== 0) {
              // 还有图片
              p.imageList.forEach(image => {
                deleteImage(image).then(resp => {
                  // 删除成功
                  if (resp.data.code === 20000) {
                    Message({
                      type: 'success',
                      message: resp.data.message
                    })
                  } else {
                    Message({
                      type: 'warning',
                      message: resp.data.message
                    })
                  }
                }).catch(() => {})
              })
            }
          }
        }
      }
    }, */

    // 深度监听introduction，执行删除图片同时从服务器上删除图片
    'spu.introduction': {
      deep: true, // 深度监听设置为 true
      handler: function (newValue, oldValue) {
        // console.log(newValue)
        // console.log(oldValue)
        if (newValue.length < oldValue.length) {
          // 需要去除<p></p>再替换
          var sub = oldValue.replace('<p>', '').replace('</p>', '').replace(
            newValue.replace('<p>', '').replace('</p>', ''), ''
          )
          // console.log(sub)
          if (sub.startsWith('<img src="http://file.xiaohong.work/xiaohong')) {
            // 删除的为图片
            // console.log('删除了图片')
            // 获取图片路径
            var url = sub.split('"')[1]
            // console.log(url)
            // 执行删除文件
            deleteImage(url).then(resp => {
              // 删除成功
              if (resp.data.code === 20000) {
                Message({
                  type: 'success',
                  message: resp.data.message
                })
              } else {
                Message({
                  type: 'warning',
                  message: resp.data.message
                })
              }
            })
          }
        }
      }
    },

    // 深度监听afterService，执行删除图片同时从服务器上删除图片
    'spu.afterService': {
      deep: true, // 深度监听设置为 true
      handler: function (newValue, oldValue) {
        // console.log(newValue)
        // console.log(oldValue)
        if (newValue.length < oldValue.length) {
          // 需要去除<p></p>再替换
          var sub = oldValue.replace('<p>', '').replace('</p>', '').replace(
            newValue.replace('<p>', '').replace('</p>', ''), ''
          )
          // console.log(sub)
          if (sub.startsWith('<img src="http://file.xiaohong.work/xiaohong')) {
            // 删除的为图片
            // console.log('删除了图片')
            // 获取图片路径
            var url = sub.split('"')[1]
            // console.log(url)
            // 执行删除文件
            deleteImage(url).then(resp => {
              // 删除成功
              if (resp.data.code === 20000) {
                Message({
                  type: 'success',
                  message: resp.data.message
                })
              } else {
                Message({
                  type: 'warning',
                  message: resp.data.message
                })
              }
            })
          }
        }
      }
    }

  },
  created () {
    // 获取树形类目
    this.findCategoryTree()
    // 获取品牌列表
    this.getBrand()
  },
  mounted () {
  },
  methods: {
    // -------------------------------------------品牌--------------------------------------------------------

    async getBrand () {
      this.isSearch = true
      await getAllBrand().then(resp => {
        // 获取成功
        if (resp.data.code === 20000) {
          this.brandList = resp.data.data
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      })
    },

    // --------------------------------------------------------类目---------------------------------------------------
    // 获取树形类目
    async findCategoryTree () {
      await getBrandTree().then(resp => {
        if (resp.data.code === 20000) {
          this.options = resp.data.data
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      })
      this.isSearch = false
    },

    // 树形类目选择改变后填充选择数据
    handleChange (value) {
      this.spu.category1Id = value[0]
      this.spu.category2Id = value[1]
      this.spu.category3Id = value[2]
    },

    // -------------------------------------------------其他-------------------------------------------------

    // 表单重置
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },

    // 跳到到表单2表单触发
    async toForm2 () {
      var that = this
      this.$refs.Form1.validate(async (valid) => {
        if (valid) {
          if (that.category.length !== 3) {
            Message({
              type: 'warning',
              message: '请选择商品分类'
            })
            return false
          }
          // 步骤条加一
          that.step.active++
          // 根据三级分类获取通用规格组及其下通用规格
          await findGeneralSpecGroupByCategoryId(this.spu.category3Id).then(resp => {
            if (resp.data.code === 20000) {
              this.generalSpecGroupList = resp.data.data
              Message({
                type: 'success',
                message: resp.data.message
              })
            } else {
              Message({
                type: 'warning',
                message: resp.data.message
              })
            }
          }).catch(() => {})
        } else {
          return false
        }
      })
    },

    // 跳到到表单3表单触发
    async toForm3 () {
      // 步骤条加一
      this.step.active++
      // 根据三级分类获取非通用规格组及其下非通用规格
      // 根据三级分类获取通用规格组及其下通用规格
      await findUnGeneralSpecGroupByCategoryId(this.spu.category3Id).then(resp => {
        if (resp.data.code === 20000) {
          this.unGeneralSpecGroupList = resp.data.data
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
    },

    // 跳到到表单4表单触发
    toForm4 () {
      // 表单验证
      for (let i = 0; i < this.skuNum; i++) {
        if (this.skuList[i].name.trim().length === 0) {
          Message({
            type: 'info',
            message: '第' + (i + 1) + '个商品名称未填哦~'
          })
          break
        } else if (this.skuList[i].num < 0) {
          console.log(this.skuList[i].num)
          Message({
            type: 'info',
            message: '第' + (i + 1) + '个商品数量填写错误哦~'
          })
          break
        } else if (this.skuList[i].price < 0) {
          Message({
            type: 'info',
            message: '第' + (i + 1) + '个商品价格填写错误哦~'
          })
          break
        } else if (this.skuList[i].imageList.length === 0) {
          Message({
            type: 'info',
            message: '第' + (i + 1) + '个商品图片未填哦~'
          })
          break
        } else if (i === this.skuNum - 1) {
          // 步骤条加一
          this.step.active++
          break
        }
      }
    },

    // 跳到到表单5表单触发
    toForm5 () {
      if (this.spu.introduction.trim().length === 0 || this.spu.introduction === '<p></p>') {
        Message({
          type: 'info',
          message: '请填写商品描述哦~'
        })
      } else {
        // 步骤条加一
        this.step.active++
      }
    },

    // 添加商品
    async addGoods () {
      this.isAdding = true
      if (this.spu.afterService.length === 0 || this.spu.introduction === '<p></p>') {
        Message({
          type: 'info',
          message: '请填写商品售后哦~'
        })
      } else {
        // await addSpu(this.goods).then(resp => {
        await addSpu({ spu: this.spu, skuList: this.skuList }).then(resp => {
          if (resp.data.code === 20000) {
            // 清空数据
            this.sku = []
            this.spu = {
              name: '', // spu名称
              caption: '', // 副标题
              brandId: '', // 品牌ID
              category1Id: 0, // 一级分类
              category2Id: 0, // 二级分类
              category3Id: 0, // 三级分类
              afterService: '', // 售后服务
              specList: [], // 规格列表
              introduction: '' // 商品介绍
            }
            this.skuList = []
            this.category = []
            this.skuSpecList = []
            this.generalSpecGroupList = []
            this.unGeneralSpecGroupLis = []
            this.skuNum = 0
            // 跳转到初始步骤条
            this.step.active = 1
            Message({
              type: 'success',
              message: resp.data.message
            })
          } else {
            Message({
              type: 'warning',
              message: resp.data.message
            })
          }
        }).catch(() => {})
      }
      this.isAdding = false
    },

    // 上一步触发
    beforeStep () {
      this.step.active--
    },

    // 文件列表移除文件时的钩子
    handleRemove (file) {
      deleteImage(file.response.data.url).then(resp => {
        // 删除成功
        if (resp.data.code === 20000) {
          this.skuList[file.response.data.index].imageList.splice(this.skuList[file.response.data.index].imageList.indexOf(file.response.data), 1)
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
    },
    // 文件上传成功钩子
    handleSuccess (response, file) {
      console.log('上传成功' + JSON.stringify(response))
      this.currentSkuIndex = response.data.index
      // file-list对应的应该是一个对象数组，但我这里数组里不想存放对象，，所以控制台会报错，报错无关紧要，忽略就行
      this.skuList[this.currentSkuIndex].imageList.push(response.data.url)
    },
    handleChangeImage (file, fileList) {
      console.log(file)
      console.log(fileList)
    }

  }
}
</script>

<style lang="less">
  .box-card {
    width: 100%;
    margin-bottom: 10px;
  }
  el-steps {
    margin-bottom: 10px;
  }
  .el-cascader .el-input .el-input__inner {
    text-overflow: ellipsis;
    width: 350px;
  }
  .el-step.is-center .el-step__description {
    padding-left: 20%;
    padding-right: 20%;
    margin-bottom: 20px;
  }
</style>
